package com.wh.wisdomsite.xbox.client.service.configClient.de;

import com.alibaba.fastjson.JSONObject;
import com.wh.wisdomsite.xbox.ba.entity.Region;
import com.wh.wisdomsite.xbox.client.utils.ConfigUserUtils;
import com.wh.wisdomsite.xbox.common.Constants;
import com.wh.wisdomsite.xbox.common.annotation.NeedInSessionType;
import com.wh.wisdomsite.xbox.common.annotation.ServiceMethod;
import com.wh.wisdomsite.xbox.common.annotation.ServiceProvider;
import com.wh.wisdomsite.xbox.common.reponse.CommonResult;
import com.wh.wisdomsite.xbox.core.session.impl.SimpleSession;
import com.wh.wisdomsite.xbox.du.entity.DustProCheckPoint;
import com.wh.wisdomsite.xbox.du.service.IDustProCheckPointService;
import com.wh.wisdomsite.xbox.me.entity.CraneProject;
import com.wh.wisdomsite.xbox.me.service.ICraneProjectService;
import com.wh.wisdomsite.xbox.pojo.configClient.de.BindProjectIn;
import com.wh.wisdomsite.xbox.pojo.configClient.de.CclDeviceIn;
import com.wh.wisdomsite.xbox.pojo.configClient.de.GetBindProjectIn;
import com.wh.wisdomsite.xbox.pojo.configClient.de.GetBindProjectOut;
import com.wh.wisdomsite.xbox.pr.entity.Project;
import com.wh.wisdomsite.xbox.pr.service.IProjectService;
import com.wh.wisdomsite.xbox.us.entity.User;
import com.wh.wisdomsite.xbox.utils.StringUtils;
import com.wh.wisdomsite.xbox.vi.entity.VideoProject;
import com.wh.wisdomsite.xbox.vi.service.IVideoProjectService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * 配置端设备Service
 * @author 丁奕
 * @version V1.0
 * @Package com.wh.wisdomsite.xbox.client.service.configClient.de
 * @date 2018年11月6日 16:11
 * @Copyright 企业版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@ServiceProvider()
public class ConfigClientDeviceService {

    private static final Log logger = LogFactory.getLog(ConfigClientDeviceService.class);

    @Autowired
    private IVideoProjectService iVideoProjectService;

    @Autowired
    private ICraneProjectService iCraneProjectService;

    @Autowired
    private IDustProCheckPointService iDustProCheckPointService;

    @Autowired
    private IProjectService iProjectService;



    /**
     * 获取项目列表
     * @param in
     * @return
     */
    @ServiceMethod(method = "zhgd.configClient.de.addDevice", title = "添加设备", version = "1.0", needInSession = NeedInSessionType.YES)
    public CommonResult addDevice(CclDeviceIn in){
        logger.info("添加设备->>zhgd.configClient.de.addDevice->>开始");
        CommonResult commonResult = new CommonResult();
        try{
            //判断入参中的必要参数
            //判断设备类型是否为空
            if(in.getDeviceType() == null || StringUtils.isEmpty(in.getDeviceType())){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage(Constants.ZHGD_CONFIG_ADD_DEVICE_TYPE_NOT_EMPTY);
                return commonResult;
            }
            //判断设备类型是否存在
            if(!CclDeviceIn.DeviceType.contains(in.getDeviceType())){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage(Constants.ZHGD_CONFIG_ADD_DEVICE_TYPE_ERROR);
                return commonResult;
            }
            //判断项目ID是否为空
            if(StringUtils.isEmpty(in.getProjectId())){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage(Constants.ZHGD_CONFIG_ADD_DEVICE_PROJECTID_NOT_EMPTY);
                return commonResult;
            }
            //判断设备名称是否为空
            if(StringUtils.isEmpty(in.getName())){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage(Constants.ZHGD_CONFIG_ADD_DEVICE_NAME_NOT_EMPTY);
                return commonResult;
            }
            //判断设备编号是否为空
            if(StringUtils.isEmpty(in.getNum())){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage(Constants.ZHGD_CONFIG_ADD_DEVICE_NUM_NOT_EMPTY);
                return commonResult;
            }
            //判断设备布点位置是否为空
            if(StringUtils.isEmpty(in.getLocate())){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage(Constants.ZHGD_CONFIG_ADD_DEVICE_LOCATE_NOT_EMPTY);
                return commonResult;
            }
            //获取当前登录的用户
            User user = ConfigUserUtils.getCurrentUser(in);
            //根据不同的设备类型，判断特殊字段是否为空,字段通过判断则进行添加操作
            //视频设备判断
            if(in.getDeviceType().equals(CclDeviceIn.DeviceType.video.name())){
                //判断视频用户是否为空
                if(StringUtils.isEmpty(in.getVideoUserId())){
                    commonResult.setCode(Constants.CODE_FAIL);
                    commonResult.setMessage(Constants.ZHGD_CONFIG_ADD_DEVICE_VIDEOUSERID_NOT_EMPTY);
                    return commonResult;
                }
                //判断视频设备用户名是否为空
                if(StringUtils.isEmpty(in.getViUserName())){
                    commonResult.setCode(Constants.CODE_FAIL);
                    commonResult.setMessage(Constants.ZHGD_CONFIG_ADD_DEVICE_VIUSERNAME_NOT_EMPTY);
                    return commonResult;
                }
                //判断视频设备用户密码是否为空
                if(StringUtils.isEmpty(in.getViPassword())){
                    commonResult.setCode(Constants.CODE_FAIL);
                    commonResult.setMessage(Constants.ZHGD_CONFIG_ADD_DEVICE_VIPASSWORD_NOT_EMPTY);
                    return commonResult;
                }
                //判断视频设备用户ip是否为空
                if(StringUtils.isEmpty(in.getVideoIp())){
                    commonResult.setCode(Constants.CODE_FAIL);
                    commonResult.setMessage(Constants.ZHGD_CONFIG_ADD_DEVICE_VIDEOIP_NOT_EMPTY);
                    return commonResult;
                }
                //添加视频设备
                VideoProject videoProject = new VideoProject();
                videoProject.setVpId(UUID.randomUUID().toString().replace("-",""));
                videoProject.setPrId(in.getProjectId());
                videoProject.setUserUuid(in.getVideoUserId());
                videoProject.setVpName(in.getName());
                videoProject.setDeviceId(in.getNum());
                videoProject.setDistributionLocation(in.getLocate());
                videoProject.setVideoUrl("http://222.85.140.116:1080/openapi/video/video.html");
                videoProject.setViUserName(in.getViUserName());
                videoProject.setViPassword(in.getViPassword());
                videoProject.setVideoIp(in.getVideoIp());
                videoProject.setCreateBy(user.getUsId());
                videoProject.setCreateDate(new Date());
                iVideoProjectService.insert(videoProject);
            //起重机械设备判断
            }else if(in.getDeviceType().equals(CclDeviceIn.DeviceType.crane.name())){
                //判断使用性质是否为空
                if(StringUtils.isEmpty(in.getCraneUseType())){
                    commonResult.setCode(Constants.CODE_FAIL);
                    commonResult.setMessage(Constants.ZHGD_CONFIG_ADD_DEVICE_CRANEUSETYPE_NOT_EMPTY);
                    return commonResult;
                }
                //判断起重机械标准配置ID是否为空
                if(StringUtils.isEmpty(in.getCraneStandardId())){
                    commonResult.setCode(Constants.CODE_FAIL);
                    commonResult.setMessage(Constants.ZHGD_CONFIG_ADD_DEVICE_CRANESTANDARDID_NOT_EMPTY);
                    return commonResult;
                }
                //添加起重机械
                CraneProject craneProject = new CraneProject();
                craneProject.setCpId(UUID.randomUUID().toString().replace("-",""));
                craneProject.setPrId(in.getProjectId());
                craneProject.setCpName(in.getName());
                craneProject.setCpCode(in.getNum());
                craneProject.setDeviceId(in.getNum());
                craneProject.setCsId(in.getCraneStandardId());
                craneProject.setDistributLoc(in.getLocate());
                craneProject.setCpUseType(in.getCraneUseType());
                craneProject.setMeIpPortInfo("");
                craneProject.setMeStatus("b42b97c83fbd4b7e8104bb12af948d6e");
                craneProject.setOnLineStatus("64bde104774443d0839e3a98e4621119");
                craneProject.setCreateBy(user.getUsId());
                craneProject.setCreateDate(new Date());
                iCraneProjectService.insert(craneProject);
            //扬尘设备
            }else{
                //添加扬尘设备
                DustProCheckPoint dustProCheckPoint = new DustProCheckPoint();
                dustProCheckPoint.setDpcpId(UUID.randomUUID().toString().replace("-",""));
                dustProCheckPoint.setPrId(in.getProjectId());
                dustProCheckPoint.setDpcpName(in.getName());
                dustProCheckPoint.setDeviceId(in.getNum());
                dustProCheckPoint.setDistributLoc(in.getLocate());
                dustProCheckPoint.setCreateBy(user.getUsId());
                dustProCheckPoint.setCreateDate(new Date());
                iDustProCheckPointService.insert(dustProCheckPoint);
            }
            commonResult.setCode(Constants.CODE_SUCCESS);
            commonResult.setMessage(Constants.CODE_SUCCESS_MSG);
            logger.info("添加设备->>zhgd.configClient.de.addDevice->>结束");
        }catch (Exception e){
            logger.error("添加设备->>zhgd.configClient.de.addDevice->>异常："+e.getMessage());
            commonResult.setCode(Constants.CODE_FAIL);
            commonResult.setMessage(Constants.CODE_FAIL_MSG);
            in.getXboxRequestContext().setException(new Exception(e.getMessage()));
            e.printStackTrace();
        }
        return commonResult;
    }


    /**
     * 请求绑定项目
     * @param in
     * @return
     */
    @ServiceMethod(method = "zhgd.configClient.de.bindProject", title = "请求绑定项目", version = "1.0", needInSession = NeedInSessionType.NO)
    public CommonResult bindProjcet(BindProjectIn in){
        CommonResult commonResult = new CommonResult();
        try{
            logger.info("请求绑定项目->>zhgd.configClient.de.bindProjcet->>开始");
            //绑定编码
            if(StringUtils.isEmpty(in.getCode())){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage(Constants.ZHGD_CONFIG_BINGPROJECT_CODE_NOT_EMPTY);
                return commonResult;
            }
            //项目编号
            if(StringUtils.isEmpty(in.getPrId())){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage(Constants.ZHGD_CONFIG_BINGPROJECT_PROJECTID_NOT_EMPTY);
                return commonResult;
            }
            //根据项目编号获取项目
            Project project = iProjectService.getById(in.getPrId());
            //项目不存在，提示
            if(null == project){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage(Constants.ZHGD_CONFIG_BINGPROJECT_PROJECT_NOT_EXIST);
                return commonResult;
            }
            //绑定项目(更改状态2：已绑定)
            Project projectUpdate = new Project();
            projectUpdate.setPrId(in.getPrId());
            projectUpdate.setPrBind("2");
            iProjectService.updateById(projectUpdate);
            //存放在缓存中
            SimpleSession session = new SimpleSession();
            session.setAttribute(Constants.CONFIG_BIND_PROJECT, in);
            in.getXboxRequestContext().addOtherSession(in.getCode(), session, 7 * 24 * 3600 * 1000);
            commonResult.setCode(Constants.CODE_SUCCESS);
            commonResult.setMessage(Constants.ZHGD_CONFIG_BINGPROJECT_SUCCESS);
            logger.info("请求绑定项目->>zhgd.configClient.de.bindProjcet->>结束");
        }catch (Exception e){
            e.printStackTrace();
            commonResult.setCode(Constants.CODE_FAIL);
            commonResult.setMessage(Constants.CODE_FAIL_MSG);
            in.getXboxRequestContext().setException(new Exception(e.getMessage()));
            logger.error("请求绑定项目->>zhgd.configClient.de.addDevice->>异常："+e.getMessage());
        }
            return commonResult;

    }



    /**
     * 获取绑定项目
     * @param in
     * @return
     */
    @ServiceMethod(method = "zhgd.configClient.de.getBindProject", title = "获取绑定项目", version = "1.0", needInSession = NeedInSessionType.NO)
    public CommonResult getBindProjcet(GetBindProjectIn in){
        CommonResult commonResult = new CommonResult();
        try{
            logger.info("获取绑定项目->>zhgd.configClient.de.getBindProject->>开始");
            //绑定编码
            if(StringUtils.isEmpty(in.getCode())){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage(Constants.ZHGD_CONFIG_GET_BINGPROJECT_CODE_NOT_EMPTY);
                return commonResult;
            }
            //从缓存中获取
            SimpleSession simpleSession = (SimpleSession) in.getXboxRequestContext().getOtherSession(in.getCode());
            if(null == simpleSession){
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage(Constants.ZHGD_CONFIG_GET_BINGPROJECT_NOTBIND_EMPTY);
                commonResult.setResult(new JSONObject());
                return commonResult;
            }
            BindProjectIn bindProjectIn = JSONObject.toJavaObject((JSONObject) simpleSession.getAttribute(Constants.CONFIG_BIND_PROJECT), BindProjectIn.class);
            if(null != bindProjectIn){
                Map<String, Object> map = iProjectService.getMapById(bindProjectIn.getPrId());
                GetBindProjectOut getBindProjectOut = new GetBindProjectOut();
                getBindProjectOut.setPrId(map.get("prId") + "");
                getBindProjectOut.setPrName(map.get("prName") + "");
                if(StringUtils.isNotEmpty(map.get("prProvice") + "")){
                    Region region = (Region) map.get("prProvice");
                    getBindProjectOut.setPrProvice(region.getRegionId() + "");
                    getBindProjectOut.setPrProviceName(region.getProvince());
                }
                if(StringUtils.isNotEmpty(map.get("prCity") + "")){
                    Region region = (Region) map.get("prCity");
                    getBindProjectOut.setPrCity(region.getRegionId() + "");
                    getBindProjectOut.setPrCityName(region.getCity());
                }
                if(StringUtils.isNotEmpty(map.get("prDistrict") + "")){
                    Region region = (Region) map.get("prDistrict");
                    getBindProjectOut.setPrDistrict(region.getRegionId() + "");
                    getBindProjectOut.setPrDistrictName(region.getDistrict() + "");
                }
                commonResult.setCode(Constants.CODE_SUCCESS);
                commonResult.setMessage(Constants.ZHGD_CONFIG_GET_BINGPROJECT_SUCCESS);
                commonResult.setResult(getBindProjectOut);
            }else{
                commonResult.setCode(Constants.CODE_SUCCESS);
                commonResult.setMessage(Constants.ZHGD_CONFIG_GET_BINGPROJECT_NOTBIND_INVALID_EMPTY);
                commonResult.setResult(new JSONObject());
            }
            logger.info("获取绑定项目->>zhgd.configClient.de.getBindProject->>结束");
        }catch (Exception e){
            e.printStackTrace();
            commonResult.setCode(Constants.CODE_FAIL);
            commonResult.setMessage(Constants.CODE_FAIL_MSG);
            in.getXboxRequestContext().setException(new Exception(e.getMessage()));
            logger.error("获取绑定项目->>zhgd.configClient.de.getBindProject->>异常："+e.getMessage());
        }
            return commonResult;

    }












}
